<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline" @submit.prevent>
      <el-form-item label="项目编号" style="width: 220px" >
        <el-input v-model="queryParams.code" placeholder="请输入项目编号" clearable />
      </el-form-item>
      <el-form-item label="项目名称" style="width: 220px">
        <el-input v-model="queryParams.name" placeholder="请输入项目名称" clearable />
      </el-form-item>
      <el-form-item label="客户" style="width: 220px">
        <el-input v-model="queryParams.client" placeholder="请输入客户名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px;">
          <el-option label="生产中" value="生产中" />
          <el-option label="完成" value="完成" />
          <el-option label="延迟生产中" value="延迟生产中" />
          <el-option label="暂停" value="暂停" />
          <el-option label="终止" value="终止" />
          <el-option label="未开始" value="未开始" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchProjectList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button v-if="isAdmin" type="primary" @click="openAddDialog">添加项目</el-button>
        <el-button v-if="isAdmin" type="primary"  @click="dialogVisible = true">导入项目</el-button>
      </el-form-item>
    </el-form>
    <!-- 导入弹窗 -->
    <el-dialog v-model="dialogVisible" title="导入项目" width="420px">
      <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :auto-upload="false"
          :before-upload="beforeUpload"
          accept=".xlsx"
          :limit="1"
          :on-change="handleFileChange"
      >
        <el-button type="primary">选择 Excel 文件</el-button>
        <div style="margin-top: 10px; font-size: 12px; color: #999;">
          仅支持 .xlsx 文件
        </div>
      </el-upload>
      <el-button
          type="success"
          style="margin-top: 10px;"
          @click="downloadTemplate"
      >
        下载导入模板
      </el-button>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport">确定导入</el-button>
      </template>
    </el-dialog>
    <!-- 表格 -->
    <Table
        :projectList="projectList"
        :columns="columns"
        :queryParams="queryParams"
        :total="total"
        :loading="loading"
        @update="handleUpdate"
        @remove="handleRemove"
        @detail="handleDetail"
        @page-change="handlePageChange"
    />


    <FormDialog
        v-model:visible="editDialogVisible"
        width="400"
        :model="currentRow"
        :columns="Columns"
        :title="dialogTitle"
        :okText="okButtonText"
        formWidth="350px"
        @save="handleSave"
    />
    <!-- 甘特图弹出框 -->
    <el-dialog
        v-model="ganttVisible"
        title="项目甘特图"
        width="80%"
        top="5vh"
    >
      <Grant
          :data="ganttData"
          height="500px"
          title="项目甘特图"
          yAxisField="code"
          bar-color="#3BA272"
      />
    </el-dialog>
    </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import Table from "@/components/el-table/Table.vue";
import FormDialog from "@/components/FormDialog/FormDialog.vue";
import router from "@/router/index.js";
import Grant from "@/components/grant/GanttChart.vue";
import { useAuthStore } from '@/stores/auth.js'
const authStore = useAuthStore()

const api = axios.create({
  baseURL: "https://pro.lkkj.xyz",
  // baseURL: "http://localhost:8080",
  timeout: 50000,
})

const isAdmin = computed(() => {
  return authStore.token === 'admin'
})

const dialogTitle = computed(() => {
  return currentRow.value.id ? '编辑项目信息' : '新增项目'
})
const okButtonText = computed(() => {
  return currentRow.value.id ? '保存' : '新增'
})


//project 表格数据
const projectList = ref([])
const userList =ref([])
const total = ref(0)
const loading = ref(false)
const columns = computed(() => {
  const baseColumns = [
    { prop: 'code', label: '项目代号', minWidth: 120 },
    { prop: 'name', label: '项目名称', minWidth: 120 },
    { prop: 'startTime', label: '立项时间', minWidth: 120 },
    { prop: 'exDeliveryTime', label: '预计交付时间', minWidth: 120 },
    { prop: 'trDeliveryTime', label: '实际交付时间', minWidth: 120 },
    { label: '进度', minWidth: 120, isProgress: true },
    { prop: 'status', label: '状态', minWidth: 120 },
    { prop: 'remark', label: '备注', minWidth: 150 }
  ]

  // 只有 admin 才加这两列
  if (isAdmin.value) {
    baseColumns.splice(2, 0,
        { prop: 'clientUsername', label: '客户账号', minWidth: 120 },
        { prop: 'client', label: '客户', minWidth: 120 }
    )
  }
  return baseColumns
})

const handleDetail = (row) => {
  router.push({
    path: '/product',
    query: { projectId: row.id,projectName: row.name  } // 假设 row.id 是项目id

  })
};

const handleUpdate = (row) => {
  currentRow.value = { ...row }
  editDialogVisible.value = true
};
const handleRemove = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除项目【${row.name}】吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const response = await api.post('/project/delete', { id: row.id });
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      await fetchProjectList();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error);
      ElMessage.error('请求失败，请稍后重试');
    }
  }
};

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    clientUsername: authStore.token,
    code: '',
    name: '',
    client: '',
    status: ''
  }
  fetchProjectList()
}

onMounted(() => {
  fetchProjectList()
})

const handlePageChange = (page) => {
  queryParams.value.pageNum = page
  fetchProjectList()
}

const queryParams = ref({
  code: '',
  name: '',
  clientUsername: authStore.token,
  client: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

const queryParamsByUser = ref({

  name: '',
  username: '',
  pageNum: 1,
  pageSize: 10
})


//编辑表单
const editDialogVisible = ref(false);
const currentRow = ref({});
const Columns = ref([

  { prop: 'code', label: '项目代号', type: 'text' },
  { prop: 'name', label: '项目名称', type: 'text' },
  {
    prop: 'clientUsername',
    label: '客户账号',
    type: 'select',
    options: [],
  },
  { prop: 'client', label: '客户', type: 'text' },
  { prop: 'startTime', label: '立项时间', type: 'date' },
  { prop: 'exDeliveryTime', label: '预计交付时间', type: 'date' },
  { prop: 'trDeliveryTime', label: '实际交付时间', type: 'date' },
  { prop: 'status', label: '状态', type: 'select', options: [
      { label: '生产中', value: '生产中' },
      { label: '完成', value: '完成' },
      { label: '延迟生产中', value: '延迟生产中' },
      { label: '暂停', value: '暂停' },
      { label: '终止', value: '终止' },
      { label: '未开始', value: '未开始' }
    ]},
  { prop: 'remark', label: '备注', type: 'text' }
])


// 获取项目列表
const fetchProjectList = async () => {
  const response = await api.get('/user/pageList', {
    params: queryParamsByUser.value
  })
  userList.value = response.data.data.list
  Columns.value[2].options = userList.value
      .filter(item => item.username !== 'admin') // 👈 关键过滤条件
      .map(item => ({
        label: item.username,
        value: item.username
      }))
  try {
    const response = await api.get('/project/list', {
      params: queryParams.value
    })
    const res = response.data
    if (res.code === 200) {
      projectList.value = res.data.list.map(item => {
        const amount = Number(item.amountSum) || 0
        const finish = Number(item.finishAmountSum) || 0
        const progress = amount > 0 ? Number(((finish / amount) * 100).toFixed(1)) : 0


        return {
          ...item,
          progress: progress  // 新增 progress 字段
        }
      })
      total.value = res.data.total

    } else {
      ElMessage.error(res.message || '获取项目列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  }
}





const handleSave = async (row) => {
  try {
    // 如果 row 里有 id，就是更新；没有 id，就是新增
    const url = row.id ? '/project/update' : '/project/add'

    const response = await api.post(url, row)

    if (response.data.code === 200) {
      ElMessage.success('保存成功')
      await fetchProjectList()
      editDialogVisible.value = false
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请稍后重试')
  }
}

const openAddDialog = () => {
  currentRow.value = {}  // 置空
  editDialogVisible.value = true
}


//甘特图
const ganttVisible = ref(false)  // 控制甘特图弹窗
const ganttData = computed(() => {
  return projectList.value.map(p => ({
    name: p.name,
    code: p.code,  // 加上项目代号
    start_time: p.startTime,
    end_time: p.exDeliveryTime // 优先使用预计交付时间
  }))
})


//导入项目相关
const dialogVisible = ref(false)
const uploadRef = ref()
const fileList = ref([])
const selectedFile = ref(null)

// 上传前校验文件类型
function beforeUpload(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    ElMessage.error('只能上传 .xlsx 文件')
  }
  return isExcel
}

// 选中文件时保存
function handleFileChange(file) {
  selectedFile.value = file.raw
}

// 点击“确定”上传文件
async function submitImport() {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择一个 Excel 文件')
    return
  }

  const formData = new FormData()
  formData.append('file', selectedFile.value)

  try {
    const res = await api.post('/excel/importProjExcel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        // Authorization: 'Bearer xxx', // 如需 token 可添加
      },
    })

    if (res.data.code === 200) {
      ElMessage.success(res.data.data || '导入成功')
      dialogVisible.value = false
      fileList.value = []
      selectedFile.value = null
      await fetchProjectList()
    } else {
      ElMessage.error(res.data.message || '导入失败')
    }
  } catch (err) {
    ElMessage.error('导入请求失败，请检查服务器或网络')
  }
}
// 下载模板按钮
function downloadTemplate() {
  // 后端模板下载接口
  // const downloadUrl = 'http://localhost:8080/excel/downloadTemplate'
  const downloadUrl = 'https://pro.lkkj.xyz/excel/downloadTemplate'
  window.open(downloadUrl)
}


</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}

</style>
